/*
 * MediaWrapper.java
 * 
 * 08/11/2009
 */
package kg.sound.player.media;

import java.io.File;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import kg.sound.player.ModelListeners;

/**
 * @author fernando
 */
public class MediaWrapper {
	
	private final LineListener lineListener = new LineListener() {
		@Override
		public void update(LineEvent e) {
			if (e.getType() == LineEvent.Type.STOP) {
				clipStopped();
			}
		}
	};
	
	private final ModelListeners listeners = new ModelListeners();
	private final File file;
	private Player player;

	public MediaWrapper(File file) {
		this.file = file;
	}

	public ModelListeners getListeners() {
		return listeners;
	}
	
	protected LineListener getLineListener() {
		return lineListener;
	}

	public File getFile() {
		return file;
	}
	
	private Player getPlayer() {
		return player;
	}
	
	private void setPlayer(Player player) {
		this.player = player;
	}
	
	public void playStream() throws Exception {
		if (!isPlaying()) {
			play(new StreamPlayer(this));
		}
	}

	public void playClip() throws Exception {
		if (!isPlaying()) {
			play(new ClipPlayer(this));
		}
	}
	
	private void play(Player player) throws Exception {
		player.play(getFile());
		setPlayer(player);
		getListeners().fireClipStarted();
	}

	public void stop() {
		if (isPlaying()) {
			getPlayer().stop();
		}
	}

	public boolean isPlaying() {
		return getPlayer() != null;
	}
	
	private void clipStopped() {
		getPlayer().purge();
		setPlayer(null);
		getListeners().fireClipStopped();
	}
}